package com.example.blog.controller;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.example.blog.entity.Image;
import com.example.blog.service.ImageService;

/**
 * 图片控制器
 */
@RestController
@RequestMapping("/api/image")
@CrossOrigin
public class ImageController {

    @Autowired
    private ImageService imageService;
    
    /**
     * 上传图片
     */
    @PostMapping("/upload")
    public Map<String, Object> uploadImage(@RequestParam("file") MultipartFile file, @RequestParam(required = false) Integer userId) {
        return imageService.uploadImage(file, userId);
    }
    
    /**
     * 获取图片列表
     */
    @GetMapping("/user/{userId}")
    public List<Image> getImagesByUserId(@PathVariable Integer userId) {
        return imageService.getImagesByUserId(userId);
    }
    
    /**
     * 获取用户未删除的图片
     */
    @GetMapping("/user/{userId}/valid")
    public List<Image> getNotDeletedImagesByUserId(@PathVariable Integer userId) {
        return imageService.getNotDeletedImagesByUserId(userId);
    }
    
    /**
     * 获取用户头像
     */
    @GetMapping("/user/{userId}/avatar")
    public Map<String, Object> getUserAvatar(@PathVariable Integer userId) {
        Map<String, Object> map = new HashMap<>();
        try {
            Image avatar = imageService.getUserAvatar(userId);
            if (avatar != null) {
                map.put("success", true);
                map.put("avatar", avatar);
            } else {
                map.put("success", false);
                map.put("message", "用户没有上传头像");
            }
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", "获取头像失败: " + e.getMessage());
        }
        return map;
    }
    
    /**
     * 标记图片为删除状态
     */
    @PutMapping("/mark-deleted/{imageId}")
    public Map<String, Object> markImageAsDeleted(@PathVariable Integer imageId) {
        Map<String, Object> map = new HashMap<>();
        boolean result = imageService.markImageAsDeleted(imageId);
        if (result) {
            map.put("success", true);
            map.put("message", "标记删除成功");
        } else {
            map.put("success", false);
            map.put("message", "标记删除失败");
        }
        return map;
    }
    
    /**
     * 物理删除图片
     */
    @DeleteMapping("/{imageId}")
    public Map<String, Object> deleteImage(@PathVariable Integer imageId) {
        Map<String, Object> map = new HashMap<>();
        boolean result = imageService.deleteImage(imageId);
        if (result) {
            map.put("success", true);
            map.put("message", "删除成功");
        } else {
            map.put("success", false);
            map.put("message", "删除失败");
        }
        return map;
    }
    
    /**
     * 根据图片名称获取图片
     */
    @GetMapping("/{imageName}")
    public ResponseEntity<Resource> getImage(@PathVariable String imageName) {
        try {
            // 获取图片信息
            Image image = imageService.getImageByName(imageName);
            if (image == null || image.getIsDeleted()) {
                return ResponseEntity.notFound().build();
            }
            
            // 获取项目路径作为基准
            String basePath = System.getProperty("user.dir");
            String imagePath = image.getImagePath();
            
            // 如果存储的是相对路径，则添加基准路径
            if (!imagePath.startsWith("/") && !imagePath.contains(":")) {
                imagePath = basePath + "/" + imagePath;
            }
            
            // 加载图片文件
            Path path = Paths.get(imagePath);
            Resource resource = new UrlResource(path.toUri());
            
            if (resource.exists() && resource.isReadable()) {
                // 根据文件扩展名确定内容类型
                MediaType mediaType = determineMediaType(imagePath);
                
                return ResponseEntity.ok()
                        .contentType(mediaType)
                        .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + image.getImageName() + "\"")
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (IOException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 通过图片路径访问图片
     */
    @GetMapping("/uploads/images/{imageName}")
    public ResponseEntity<Resource> getImageByPath(@PathVariable String imageName) {
        try {
            // 构建图片路径
            String basePath = System.getProperty("user.dir");
            String imagePath = basePath + "/uploads/images/" + imageName;
            
            // 加载图片文件
            Path path = Paths.get(imagePath);
            Resource resource = new UrlResource(path.toUri());
            
            if (resource.exists() && resource.isReadable()) {
                // 根据文件扩展名确定内容类型
                MediaType mediaType = determineMediaType(imagePath);
                
                return ResponseEntity.ok()
                        .contentType(mediaType)
                        .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + imageName + "\"")
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (IOException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 根据文件路径确定媒体类型
     */
    private MediaType determineMediaType(String path) {
        if (path == null) {
            return MediaType.IMAGE_JPEG;
        }
        
        path = path.toLowerCase();
        if (path.endsWith(".jpg") || path.endsWith(".jpeg")) {
            return MediaType.IMAGE_JPEG;
        } else if (path.endsWith(".png")) {
            return MediaType.IMAGE_PNG;
        } else if (path.endsWith(".gif")) {
            return MediaType.IMAGE_GIF;
        } else {
            return MediaType.IMAGE_JPEG; // 默认JPEG
        }
    }
} 